package com.fa4j.third.file.s3.adapter;

import com.fa4j.third.base.adapter.AbstractThirdServiceAdapter;
import com.fa4j.third.file.model.*;
import com.fa4j.third.file.service.ThirdFileService;
import io.minio.*;
import lombok.Setter;
import lombok.SneakyThrows;
import org.springframework.util.StreamUtils;

import java.io.InputStream;
import java.io.OutputStream;

@Setter
public class S3FileServiceAdapter extends AbstractThirdServiceAdapter implements ThirdFileService {

    private String urlPrefix;
    private Long maxFileSize;
    private String fileTypes;
    private String endpoint;
    private String bucket;
    private String accessKeyId;
    private String accessKeySecret;
    private String region;

    private MinioClient client;

    /**
     * 初始化
     */
    @Override
    public void init() {
        super.init();
        client = MinioClient.builder()
                .endpoint(endpoint)
                .region(region)
                .credentials(accessKeyId, accessKeySecret)
                .build();
    }

    @Override
    @SneakyThrows
    public void close() {
        client.close();
    }

    @Override
    @SneakyThrows
    public void upload(ThirdFileUploadCmd cmd, InputStream inputStream) {
        if (cmd.getFileSize() > maxFileSize) {
            //操过文件大小
            throw ThirdFileError.MAX_SIZE_LIMITED.build(cmd.getFileSize() / 1204 + "kb");
        }
        if (!fileTypes.contains(cmd.getFileExtension().toLowerCase())) {
            throw ThirdFileError.NOT_SUPPORT_FILE_TYPE.build();
        }
        client.putObject(
                PutObjectArgs.builder()
                        .bucket(bucket)
                        .contentType(cmd.getContentType())
                        .object(cmd.getFilePath())
                        .stream(inputStream, cmd.getFileSize(), 5 * 1024 * 1024)
                        .build()
        );
    }


    @Override
    @SneakyThrows
    public void remove(ThirdFileRemoveCmd cmd) {
        client.removeObject(RemoveObjectArgs.builder()
                .bucket(bucket)
                .object(cmd.getFilePath())
                .build());

    }

    @Override
    @SneakyThrows
    public void download(ThirdFileDownloadCmd cmd, OutputStream outputStream) {
        try (GetObjectResponse response = client.getObject(GetObjectArgs.builder()
                .bucket(bucket)
                .object(cmd.getFilePath())
                .build())) {
            StreamUtils.copy(response, outputStream);
        }
    }

    @Override
    public String getFileUrl(ThirdFileUrlCmd cmd) {
        return urlPrefix + getProps().getBizCode() + cmd.getFilePath();
    }
}
